eric897
Goto Top

Hilfe bei DataGrid und qwinsta Powershell

Hallo zusammen,

ich habe ein kleines Problem und zwar wie kann ich von dem Befehl qwinsta.exe die Liste in ein DataGrid Object einfügen.

$(qwinsta.exe /Server:Servername | findstr „Aktiv“) -replace „^[ >]“ , „“ -replace „ +“ , „,“

Damit würde ich ja das ganze in ein String umwandeln aber wie bekomme ich das in ein DataGrid?

Danke im Vorraus!

Content-Key: 5974239010

Url: https://administrator.de/contentid/5974239010

Printed on: May 20, 2024 at 18:05 o'clock

Mitglied: 7907292512
7907292512 Sep 12, 2023 updated at 09:09:45 (UTC)
Goto Top
Member: em-pie
em-pie Sep 12, 2023 at 09:09:04 (UTC)
Goto Top
Moin,

ich würde das "anders" handhaben:
Quelle: https://stackoverflow.com/questions/23445175/qwinsta-serversomesrv-equiv ...
function Get-TSSessions {
    param(
        $ComputerName = 'localhost'  
    )

    $output = qwinsta /server:$ComputerName
    if ($null -eq $output) {
        # An error occured. Abort
        return
    }

    # Get column names and locations from fixed-width header
    $columns = [regex]::Matches($output[0],'(?<=\s)\w+')  
    $output | Select-Object -Skip 1 | Foreach-Object {
        [string]$line = $_

        $session = [ordered]@{}
        for ($i=0; $i -lt $columns.Count; $i++) {
            $currentColumn = $columns[$i]
            $columnName = $currentColumn.Value

            if ($i -eq $columns.Count-1) {
                # Last column, get rest of the line
                $columnValue = $line.Substring($currentColumn.Index).Trim()
            } else {
                $lengthToNextColumn = $columns[$i+1].Index - $currentColumn.Index
                $columnValue = $line.Substring($currentColumn.Index, $lengthToNextColumn).Trim()
            }

            $session.$columnName = $columnValue.Trim()
        }

        # Return session as object
        [pscustomobject]$session
    }
}

Und hier dann der Aufruf/ die Nutzung:
Get-TSSessions -ComputerName "localhost" | Format-Table -AutoSize  

SESSIONNAME USERNAME ID STATE  TYPE DEVICE
----------- -------- -- -----  ---- ------
services             0  Disc
console     Frode    1  Active

#This is objects, so we can manipulate the results to get the info we want. Active sessions only:
Get-TSSessions -ComputerName "localhost" | Where-Object State -eq 'Active' | Format-Table -AutoSize SessionName, UserName, ID  

SESSIONNAME USERNAME ID
----------- -------- --
console     Frode    1
Member: Kraemer
Kraemer Sep 12, 2023 updated at 09:10:29 (UTC)
Goto Top
Zitat von @Eric897:

$(qwinsta.exe /Server:Servername | findstr „Aktiv“) -replace „^[ >]“ , „“ -replace „ +“ , „,“

Damit würde ich ja das ganze in ein String umwandeln aber wie bekomme ich das in ein DataGrid?

 (qwinsta /server:$ServerName | foreach { (($_.trim() -replace “s+”,”,”))} | ConvertFrom-Csv) | Out-GridView

Inspiration: https://discoposse.com/2012/10/20/finding-rdp-sessions-on-servers-using- ...
Member: Eric897
Eric897 Sep 12, 2023 at 09:10:22 (UTC)
Goto Top
Zitat von @em-pie:

Moin,

ich würde das "anders" handhaben:
Quelle: https://stackoverflow.com/questions/23445175/qwinsta-serversomesrv-equiv ...
function Get-TSSessions {
    param(
        $ComputerName = 'localhost'  
    )

    $output = qwinsta /server:$ComputerName
    if ($null -eq $output) {
        # An error occured. Abort
        return
    }

    # Get column names and locations from fixed-width header
    $columns = [regex]::Matches($output[0],'(?<=\s)\w+')  
    $output | Select-Object -Skip 1 | Foreach-Object {
        [string]$line = $_

        $session = [ordered]@{}
        for ($i=0; $i -lt $columns.Count; $i++) {
            $currentColumn = $columns[$i]
            $columnName = $currentColumn.Value

            if ($i -eq $columns.Count-1) {
                # Last column, get rest of the line
                $columnValue = $line.Substring($currentColumn.Index).Trim()
            } else {
                $lengthToNextColumn = $columns[$i+1].Index - $currentColumn.Index
                $columnValue = $line.Substring($currentColumn.Index, $lengthToNextColumn).Trim()
            }

            $session.$columnName = $columnValue.Trim()
        }

        # Return session as object
        [pscustomobject]$session
    }
}

Und hier dann der Aufruf/ die Nutzung:
Get-TSSessions -ComputerName "localhost" | Format-Table -AutoSize  

SESSIONNAME USERNAME ID STATE  TYPE DEVICE
----------- -------- -- -----  ---- ------
services             0  Disc
console     Frode    1  Active

#This is objects, so we can manipulate the results to get the info we want. Active sessions only:
Get-TSSessions -ComputerName "localhost" | Where-Object State -eq 'Active' | Format-Table -AutoSize SessionName, UserName, ID  

SESSIONNAME USERNAME ID
----------- -------- --
console     Frode    1

Danke aber das Problem ist, das ich das in einer GUI haben möchte
Member: Eric897
Eric897 Sep 12, 2023 at 09:12:14 (UTC)
Goto Top
Add-Type -assembly System.Windows.Forms

#$form ist das Fenster ansich
#$tbl ist die Tabelle

#Schaltet so gesehen das Feature frei, Windows Forms in seiner Powershell zu nutzen
$form = New-Object System.Windows.Forms.Form

#Größe des Fensters bestimmen
$form.Size = New-Object System.Drawing.Size(900,600)

#Erstelle die Tabelle
$tbl = New-Object System.Windows.Forms.DataGridView

#Definiere Größe der Tabelle
$tbl.Size = New-Object System.Drawing.Size(900,500)
$tbl.Location = New-Object System.Drawing.Point (0, 50)

#Gebe die Funktion das Fenster zu steuern
$form.Controls.Add($tbl)

#Gebe an wie viele Spalten erstellt werden solln
$tbl.ColumnCount = 5

#Definiere den Spaltenkopf 
$tbl.ColumnHeadersVisible = $true

$tbl.Columns[0].Name = "Sitzungsangaben"  
$tbl.Columns[1].Name = "Benutzername"  
$tbl.Columns[2].Name = "ID"  
$tbl.Columns[3].Name = "Status"  
$tbl.Columns[4].Name = "Servername"  

$tbl.Columns[0].Width = 175
$tbl.Columns[1].Width = 175
$tbl.Columns[2].Width = 150
$tbl.Columns[3].Width = 150
$tbl.Columns[4].Width = 200

Das wäre der Code für die Tabelle wo die Werte rein sollten
Mitglied: 7907292512
7907292512 Sep 12, 2023 updated at 09:31:55 (UTC)
Goto Top
Siehe die Links oben daraus siehst du wie es geht. ArrayList erstellen, Objekte hinzufügen und Array-List als Source des Datagrids angeben.
Member: Eric897
Eric897 Sep 12, 2023 at 09:29:14 (UTC)
Goto Top
Zitat von @7907292512:

Siehe Links oben daraus siehst du wie es geht. ArrayList erstellen, Objekte hinzufügen und Array-List als Source des Datagrids angeben.

Wo oben links :D
Mitglied: 7907292512
7907292512 Sep 12, 2023 at 09:31:41 (UTC)
Goto Top
Member: Eric897
Eric897 Sep 12, 2023 at 09:49:53 (UTC)
Goto Top

Dumme Frage bin leider garnicht erfahren in Powershell aber wie kann ich die Array List denn erstellen.

Kann ich mithilfe einer Schleife das auch auffüllen lassen?
Member: colinardo
Solution colinardo Sep 12, 2023 updated at 09:55:01 (UTC)
Goto Top
Servus @Eric897 .
Qwinsta & Co als Strings zu parsen ist nicht nötig und ehrlich gesagt von Vor-Vor-Gestern. Es gibt native Methoden zum Abfragen der Sessions (Siehe Link den @7907292512 schon gepostet hat: Powershell Script Angemeldete User und ClientPC). Der Vorteil hierbei man erhält sogar noch mehr Infos wie die IP des Remote-Hosts und weitere wie bspw. die Auflösung und Farbtiefe des Clients gleich mitgeliefert.
Zum füttern eines DataGridView-Controls reicht es dann diese Objekte in einer ArrayList zu laden und der DataSource-Property des DataGridViews zu übergeben.

Ein Beispiel
Add-Type -A System.Windows.Forms
Add-Type '  
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Net;

namespace WTS {
    public static class Sessions {
        public enum WTS_CONNECTSTATE_CLASS {
            WTSActive,
            WTSConnected,
            WTSConnectQuery,
            WTSShadow,
            WTSDisconnected,
            WTSIdle,
            WTSListen,
            WTSReset,
            WTSDown,
            WTSInit
        }
        public enum WTS_INFO_CLASS
        {
             WTSInitialProgram,
             WTSApplicationName,
             WTSWorkingDirectory,
             WTSOEMId,
             WTSSessionId,
             WTSUserName,
             WTSWinStationName,
             WTSDomainName,
             WTSConnectState,
             WTSClientBuildNumber,
             WTSClientName,
             WTSClientDirectory,
             WTSClientProductId,
             WTSClientHardwareId,
             WTSClientAddress,
             WTSClientDisplay,
             WTSClientProtocolType,
             WTSIdleTime,
             WTSLogonTime,
             WTSIncomingBytes,
             WTSOutgoingBytes,
             WTSIncomingFrames,
             WTSOutgoingFrames,
             WTSClientInfo,
             WTSSessionInfo
        }
        
        [StructLayout(LayoutKind.Sequential)]
        private struct WTS_CLIENT_ADDRESS
        {
            public uint AddressFamily;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
            public byte[] Address;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct WTS_SESSION_INFO_1 {
            public Int32 ExecEnvId;
            public WTS_CONNECTSTATE_CLASS State;
            public Int32 SessionId;
            [MarshalAs(UnmanagedType.LPStr)]
            public String pSessionName;
            [MarshalAs(UnmanagedType.LPStr)]
            public String pHostName;
            [MarshalAs(UnmanagedType.LPStr)]
            public String pUserName;
            [MarshalAs(UnmanagedType.LPStr)]
            public String pDomainName;
            [MarshalAs(UnmanagedType.LPStr)]
            public String pFarmName;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct WTS_CLIENT_DISPLAY {
            public int HorizontalResolution;
            public int VerticalResolution;
            public int ColorDepth;
        }

        [DllImport("wtsapi32.dll", SetLastError = true)]    
        static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);

        [DllImport("wtsapi32.dll")]    
        static extern void WTSCloseServer(IntPtr hServer);

        [DllImport("Wtsapi32.dll", SetLastError = true), SuppressUnmanagedCodeSecurity]    
        static extern int WTSEnumerateSessionsEx(IntPtr hServer, ref int pLevel, int Filter, ref IntPtr ppSessionInfo, ref int pCount);

        [DllImport("wtsapi32.dll", SetLastError = true)]    
        static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out IntPtr ppBuffer, out int pBytesReturned);

        [DllImport("wtsapi32.dll")]    
        static extern void WTSFreeMemory(IntPtr pMemory);

        public class TerminalSession {
            public int SessionId;
            public WTS_CONNECTSTATE_CLASS SessionState;
            public string Host;
            public string SessionName;
            public string UserName;
            public object RemoteHost;
            public string DomainName;
            public string FarmName;
            public int ClientHorizontalResolution;
            public int ClientVerticalResolution;
            public string ClientColorDepth;
        }

        public static List<TerminalSession> GetTSSessions(string Server = "") {    
            IntPtr server = IntPtr.Zero;
            List<TerminalSession> result = new List<TerminalSession>();
            if (Server != "") {    
                server = WTSOpenServer(Server);
            }
            try {

                IntPtr ppSessionInfo = IntPtr.Zero;
                Int32 count = 0;
                Int32 pLevel = 1;
                Int32 retval = WTSEnumerateSessionsEx(server, ref pLevel, 0, ref ppSessionInfo, ref count);
                Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO_1));
                Int64 current = (Int64)ppSessionInfo;
                IntPtr buffer;
                int strLen;
                Hashtable colordepths = new Hashtable() {{ 1, "4bit"},{ 2, "8bit"},{ 4, "16bit"},{ 8, "24bit"},{ 16, "15bit"},{ 24, "24bit"},{ 32, "32bit"}};    

                if (retval != 0) {
                    for (int i = 0; i < count; i++) {
                        WTS_SESSION_INFO_1 si = (WTS_SESSION_INFO_1)Marshal.PtrToStructure((IntPtr)current, typeof(WTS_SESSION_INFO_1));
                        current += dataSize;
                        
                        // get remote host information
                        object remotehost = null;
                        if (WTSQuerySessionInformation(server,si.SessionId ,WTS_INFO_CLASS.WTSClientAddress, out buffer, out strLen) && strLen > 1){
                            WTS_CLIENT_ADDRESS c_address  = (WTS_CLIENT_ADDRESS)Marshal.PtrToStructure(buffer, typeof(WTS_CLIENT_ADDRESS));
                            if (c_address.AddressFamily == 2 && c_address.Address[2] != 0){
                                // AF_INET (IPv4 address)
                                remotehost = new IPAddress(new byte[] {c_address.Address[2],c_address.Address[3],c_address.Address[4],c_address.Address[5]});
                            } else if (c_address.AddressFamily == 23){
                                // AF_INET6 (IPv6 address)
                                byte[] bv6 = new byte[16];
                                Array.Copy(c_address.Address,2,bv6,0,16);
                                remotehost = new IPAddress(bv6);
                            } else {
                                remotehost = new IPAddress(new byte[] {0,0,0,0});
                            }
                            WTSFreeMemory(buffer);
                        }
                        // get remote display information
                        WTS_CLIENT_DISPLAY oClientDisplay = new WTS_CLIENT_DISPLAY();
                        if (WTSQuerySessionInformation(server,si.SessionId ,WTS_INFO_CLASS.WTSClientDisplay, out buffer, out strLen) && strLen > 1){
                            oClientDisplay = (WTS_CLIENT_DISPLAY)Marshal.PtrToStructure(buffer, oClientDisplay.GetType());
                            WTSFreeMemory(buffer);
                        }

                        result.Add(new TerminalSession() {
                            SessionId = si.SessionId,
                            SessionState = si.State,
                            SessionName = si.pSessionName,
                            Host = Server,
                            RemoteHost = remotehost,
                            UserName = si.pUserName,
                            DomainName = si.pDomainName,
                            FarmName = si.pFarmName,
                            ClientHorizontalResolution = oClientDisplay.HorizontalResolution, 
                            ClientVerticalResolution = oClientDisplay.VerticalResolution,
                            ClientColorDepth = (string)colordepths[oClientDisplay.ColorDepth]
                        });
                    }

                    WTSFreeMemory(ppSessionInfo);
                }
            }catch(Exception ex) {
                throw new Exception(ex.Message);
            } finally {
                WTSCloseServer(server);
            }
            return result;
        }
    }
}
'  
# Get Logon-Sessions
$sessions = [WTS.Sessions]::GetTSSessions('localhost') | select SessionId,Host,RemoteHost,SessionState,Sessionname,DomainName,Username,ClientHorizontalResolution,ClientVerticalResolution,ClientColorDepth  
# create form
$form = New-Object System.Windows.Forms.Form -P @{
    ClientSize = '800,400'  
    Text = "Logon-Sessions"  
    # load event
    add_Load = {
        # create arraylist object
        $list = New-Object System.Collections.ArrayList
        # add session objects to arraylist
        $list.AddRange(@($sessions))
        # assign the arraylist to the datasource property of the DataGridview
        $dgv.DataSource = $list
    }
}
# create datagridview object
$dgv = [System.Windows.Forms.DataGridView]@{
    Dock = "Fill"  
}
# add controls
$form.Controls.Add($dgv)
# show form
[void]$form.ShowDialog()

Grüße Uwe
Member: Eric897
Eric897 Sep 12, 2023 at 09:59:22 (UTC)
Goto Top
Zitat von @colinardo:

Servus @Eric897 .
Qwinsta & Co als Strings zu parsen ist nicht nötig und ehrlich gesagt von Vor-Vor-Gestern. Es gibt native Methoden zum Abfragen der Sessions (Siehe Link den @7907292512 schon gepostet hat: Powershell Script Angemeldete User und ClientPC). Der Vorteil hierbei man erhält sogar noch mehr Infos wie die IP des Remote-Hosts und weitere wie bspw. die Auflösung und Farbtiefe des Clients gleich mitgeliefert.
Zum füttern eines DataGridView-Controls reicht es dann diese Objekte in einer ArrayList zu laden und der DataSource-Property des DataGridViews zu übergeben.

Ein Beispiel
Add-Type -A System.Windows.Forms
Add-Type '  
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Net;

namespace WTS {
    public static class Sessions {
        public enum WTS_CONNECTSTATE_CLASS {
            WTSActive,
            WTSConnected,
            WTSConnectQuery,
            WTSShadow,
            WTSDisconnected,
            WTSIdle,
            WTSListen,
            WTSReset,
            WTSDown,
            WTSInit
        }
        public enum WTS_INFO_CLASS
        {
             WTSInitialProgram,
             WTSApplicationName,
             WTSWorkingDirectory,
             WTSOEMId,
             WTSSessionId,
             WTSUserName,
             WTSWinStationName,
             WTSDomainName,
             WTSConnectState,
             WTSClientBuildNumber,
             WTSClientName,
             WTSClientDirectory,
             WTSClientProductId,
             WTSClientHardwareId,
             WTSClientAddress,
             WTSClientDisplay,
             WTSClientProtocolType,
             WTSIdleTime,
             WTSLogonTime,
             WTSIncomingBytes,
             WTSOutgoingBytes,
             WTSIncomingFrames,
             WTSOutgoingFrames,
             WTSClientInfo,
             WTSSessionInfo
        }
        
        [StructLayout(LayoutKind.Sequential)]
        private struct WTS_CLIENT_ADDRESS
        {
            public uint AddressFamily;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
            public byte[] Address;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct WTS_SESSION_INFO_1 {
            public Int32 ExecEnvId;
            public WTS_CONNECTSTATE_CLASS State;
            public Int32 SessionId;
            [MarshalAs(UnmanagedType.LPStr)]
            public String pSessionName;
            [MarshalAs(UnmanagedType.LPStr)]
            public String pHostName;
            [MarshalAs(UnmanagedType.LPStr)]
            public String pUserName;
            [MarshalAs(UnmanagedType.LPStr)]
            public String pDomainName;
            [MarshalAs(UnmanagedType.LPStr)]
            public String pFarmName;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct WTS_CLIENT_DISPLAY {
            public int HorizontalResolution;
            public int VerticalResolution;
            public int ColorDepth;
        }

        [DllImport("wtsapi32.dll", SetLastError = true)]    
        static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);

        [DllImport("wtsapi32.dll")]    
        static extern void WTSCloseServer(IntPtr hServer);

        [DllImport("Wtsapi32.dll", SetLastError = true), SuppressUnmanagedCodeSecurity]    
        static extern int WTSEnumerateSessionsEx(IntPtr hServer, ref int pLevel, int Filter, ref IntPtr ppSessionInfo, ref int pCount);

        [DllImport("wtsapi32.dll", SetLastError = true)]    
        static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out IntPtr ppBuffer, out int pBytesReturned);

        [DllImport("wtsapi32.dll")]    
        static extern void WTSFreeMemory(IntPtr pMemory);

        public class TerminalSession {
            public int SessionId;
            public WTS_CONNECTSTATE_CLASS SessionState;
            public string Host;
            public string SessionName;
            public string UserName;
            public object RemoteHost;
            public string DomainName;
            public string FarmName;
            public int ClientHorizontalResolution;
            public int ClientVerticalResolution;
            public string ClientColorDepth;
        }

        public static List<TerminalSession> GetTSSessions(string Server = "") {    
            IntPtr server = IntPtr.Zero;
            List<TerminalSession> result = new List<TerminalSession>();
            if (Server != "") {    
                server = WTSOpenServer(Server);
            }
            try {

                IntPtr ppSessionInfo = IntPtr.Zero;
                Int32 count = 0;
                Int32 pLevel = 1;
                Int32 retval = WTSEnumerateSessionsEx(server, ref pLevel, 0, ref ppSessionInfo, ref count);
                Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO_1));
                Int64 current = (Int64)ppSessionInfo;
                IntPtr buffer;
                int strLen;
                Hashtable colordepths = new Hashtable() {{ 1, "4bit"},{ 2, "8bit"},{ 4, "16bit"},{ 8, "24bit"},{ 16, "15bit"},{ 24, "24bit"},{ 32, "32bit"}};    

                if (retval != 0) {
                    for (int i = 0; i < count; i++) {
                        WTS_SESSION_INFO_1 si = (WTS_SESSION_INFO_1)Marshal.PtrToStructure((IntPtr)current, typeof(WTS_SESSION_INFO_1));
                        current += dataSize;
                        
                        // get remote host information
                        object remotehost = null;
                        if (WTSQuerySessionInformation(server,si.SessionId ,WTS_INFO_CLASS.WTSClientAddress, out buffer, out strLen) && strLen > 1){
                            WTS_CLIENT_ADDRESS c_address  = (WTS_CLIENT_ADDRESS)Marshal.PtrToStructure(buffer, typeof(WTS_CLIENT_ADDRESS));
                            if (c_address.AddressFamily == 2 && c_address.Address[2] != 0){
                                // AF_INET (IPv4 address)
                                remotehost = new IPAddress(new byte[] {c_address.Address[2],c_address.Address[3],c_address.Address[4],c_address.Address[5]});
                            } else if (c_address.AddressFamily == 23){
                                // AF_INET6 (IPv6 address)
                                byte[] bv6 = new byte[16];
                                Array.Copy(c_address.Address,2,bv6,0,16);
                                remotehost = new IPAddress(bv6);
                            } else {
                                remotehost = new IPAddress(new byte[] {0,0,0,0});
                            }
                            WTSFreeMemory(buffer);
                        }
                        // get remote display information
                        WTS_CLIENT_DISPLAY oClientDisplay = new WTS_CLIENT_DISPLAY();
                        if (WTSQuerySessionInformation(server,si.SessionId ,WTS_INFO_CLASS.WTSClientDisplay, out buffer, out strLen) && strLen > 1){
                            oClientDisplay = (WTS_CLIENT_DISPLAY)Marshal.PtrToStructure(buffer, oClientDisplay.GetType());
                            WTSFreeMemory(buffer);
                        }

                        result.Add(new TerminalSession() {
                            SessionId = si.SessionId,
                            SessionState = si.State,
                            SessionName = si.pSessionName,
                            Host = Server,
                            RemoteHost = remotehost,
                            UserName = si.pUserName,
                            DomainName = si.pDomainName,
                            FarmName = si.pFarmName,
                            ClientHorizontalResolution = oClientDisplay.HorizontalResolution, 
                            ClientVerticalResolution = oClientDisplay.VerticalResolution,
                            ClientColorDepth = (string)colordepths[oClientDisplay.ColorDepth]
                        });
                    }

                    WTSFreeMemory(ppSessionInfo);
                }
            }catch(Exception ex) {
                throw new Exception(ex.Message);
            } finally {
                WTSCloseServer(server);
            }
            return result;
        }
    }
}
'  
# Get Logon-Sessions
$sessions = [WTS.Sessions]::GetTSSessions('localhost') | select SessionId,Host,RemoteHost,SessionState,Sessionname,DomainName,Username,ClientHorizontalResolution,ClientVerticalResolution,ClientColorDepth  
# create form
$form = New-Object System.Windows.Forms.Form -P @{
    ClientSize = '800,400'  
    Text = "Logon-Sessions"  
    # load event
    add_Load = {
        # create arraylist object
        $list = New-Object System.Collections.ArrayList
        # add session objects to arraylist
        $list.AddRange(@($sessions))
        # assign the arraylist to the datasource property of the DataGridview
        $dgv.DataSource = $list
    }
}
# create datagridview object
$dgv = [System.Windows.Forms.DataGridView]@{
    Dock = "Fill"  
}
# add controls
$form.Controls.Add($dgv)
# show form
[void]$form.ShowDialog()

Grüße Uwe

Okay danke dir sieht gut aus ich schau ma wie ichs damit mach! :D
Member: Eric897
Eric897 Sep 12, 2023 at 10:03:01 (UTC)
Goto Top
Kann ich dann bei dem Select Befehl auch irgendwie den Gerätename hinzufügen bsw abfragen?
Member: colinardo
colinardo Sep 12, 2023 updated at 10:07:36 (UTC)
Goto Top
Zitat von @Eric897:
Kann ich dann bei dem Select Befehl auch irgendwie den Gerätename hinzufügen bsw abfragen?
Du kannst die Ausgabe jederzeit filtern mit einem in die Pipeline eingeschalteten Where-Object
$sessions = [WTS.Sessions]::GetTSSessions('localhost') | select SessionId,Host,RemoteHost,SessionState,Sessionname,DomainName,Username,ClientHorizontalResolution,ClientVerticalResolution,ClientColorDepth | where-object {$_.RemoteHost -eq '192.168.1.20'}  

p.s. bitte nicht immer komplett zitieren, darunter leidet die Übersicht. Merci!
Member: Eric897
Eric897 Sep 12, 2023 at 10:10:22 (UTC)
Goto Top
Okay aber das Problem ist wie kann ich mehrere Server abfragen dann face-sad
Member: colinardo
colinardo Sep 12, 2023 updated at 10:16:10 (UTC)
Goto Top
Zitat von @Eric897:
Okay aber das Problem ist wie kann ich mehrere Server abfragen dann face-sad
Steht doch in meinem verlinkten Beitrag! Es reicht eine einfache ForEach Schleife über deine Server
$servers = "Server1","Server2"  
$sessions = $servers | %{[WTS.Sessions]::GetTSSessions($_) | select SessionId,Host,RemoteHost,SessionState,Sessionname,DomainName,Username,ClientHorizontalResolution,ClientVerticalResolution,ClientColorDepth}

Ich empfehle als Lektüre:
Powershell Leitfaden für Anfänger
Member: Eric897
Eric897 Sep 12, 2023 at 10:19:41 (UTC)
Goto Top
Zitat von @colinardo:

Zitat von @Eric897:
Okay aber das Problem ist wie kann ich mehrere Server abfragen dann face-sad
Steht doch in meinem verlinkten Beitrag! Es reicht eine einfache ForEach Schleife über deine Server
$servers = "Server1","Server2"  
$sessions = $servers | %{[WTS.Sessions]::GetTSSessions($_) | select SessionId,Host,RemoteHost,SessionState,Sessionname,DomainName,Username,ClientHorizontalResolution,ClientVerticalResolution,ClientColorDepth}

Ich empfehle als Lektüre:
Powershell Leitfaden für Anfänger

Oh sorry habs mal ergänzt und es geht! Den Rest kriege ich denke selbst hin, muss noch paar Buttons hinzufügen. Vielen Dank!
Member: Eric897
Eric897 Sep 12, 2023 at 12:11:21 (UTC)
Goto Top
Ich würde jetzt noch gerne die Spiegelfunktion nutzen aber geht nicht so ganz :

$dBttn.Add_Click(
{
$SelectedItem = $dList.SelectedItems[0]
if ($SelectedItem -eq $null){
[System.Windows.Forms.MessageBox]::Show(„Select a user session to connect „)
}else{
$session_id = $SelectedItem.subitems[2].text
$Server = $SelectedItem.subitems[4].text
$(mstsc /v:$SERVER /shadow:$session_id /control)
#[System.Windows.Forms.MessageBox]::Show($session_id)
}
}
)

Fällt irgendjmd ein Fehler auf
Member: Kraemer
Kraemer Sep 12, 2023 at 12:28:30 (UTC)
Goto Top
Member: Eric897
Eric897 Sep 12, 2023 at 12:48:43 (UTC)
Goto Top


Danke habs mi ma durcchgelesen aber was bringt es letzlich?
Der sagt mir folgendes:

Es ist nicht möglich, einen Index auf ein Null Array anzuwenden


$SelectedItem = $dgv.SelectedItems[0]
Member: Kraemer
Kraemer Sep 12, 2023 at 13:13:25 (UTC)
Goto Top
sieh an, dass hatte ich sogar noch übersehen. Da kannst du mal sehen, wie Fehlermeldungen weiterhelfen. An sich ist die Fehlermeldung eindeutig
Member: Eric897
Eric897 Sep 12, 2023 at 13:17:39 (UTC)
Goto Top
Okay ich schaue mal danke dir !
Member: Eric897
Eric897 Sep 12, 2023 at 13:39:47 (UTC)
Goto Top
Ich hab nochma geschaut auch auf anderen Seiten ich komme allerdings auch nicht drauf. Ich verstehe den Fehler irgendwie auch, aber auch irgendwie nicht. Vielleicht kann mir ja jmd einen "Gedankenschubs" geben.
Bin auch erst noch in meiner Ausbildung und prinzipiell nur ein wenig C# Kenntnisse :D
Member: Kraemer
Kraemer Sep 12, 2023 at 13:41:54 (UTC)
Goto Top
$SelectedItem = $dList.SelectedItems[0]
if ($SelectedItem -eq $null){

wird zu

if ($null -eq $dList.SelectedItems[0]){

BTW: benutze bitte Code-Tags
Member: colinardo
colinardo Sep 12, 2023 updated at 13:59:18 (UTC)
Goto Top
Für mein Beispiel oben mit dem DatagridView-Control, über das Doppelklick-Event der ausgewählten Zeile sähe das bspw. so aus

# ...
# create datagridview object
$dgv = New-Object System.Windows.Forms.DataGridView -P @{
    Dock = 'Fill'  
    ReadOnly = $true
    SelectionMode = 'FullRow'  
    add_CellMouseDoubleClick = {
        if ($dgv.selectedRows.Count -gt 0){
            $server = $dgv.SelectedRows[0].Cells['Host'].Value  
            $sessionid = $dgv.SelectedRows[0].Cells['SessionId'].Value  
            if ($server -and $sessionid -gt 0){
                & mstsc /v:$server /shadow:$sessionid /control
            }
        }
    }
}
# ...
DataGridView Klasse
Member: Eric897
Eric897 Sep 12, 2023 at 13:58:21 (UTC)
Goto Top
Okay ausprobiert und geht leider nicht wie gedacht. Ich hab so das Gefühl, das er das aus dem DataGrid nicht wirklich auswählt
Member: Eric897
Eric897 Sep 12, 2023 at 14:12:39 (UTC)
Goto Top
So habs gefixt :D

Sehr geil, danke an alle die geholfen haben face-smile